package com.huaxinkaiye.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.huaxinkaiye.R;
import com.huaxinkaiye.Zxing.CaptureActivity;
import com.huaxinkaiye.adapter.ListAdapter;
import com.huaxinkaiye.adapter.NoticeAdapter;
import com.huaxinkaiye.application.HuaXinApplication;
import com.huaxinkaiye.bean.ListBean;
import com.huaxinkaiye.bean.RowsBean;
import com.huaxinkaiye.utils.ProgressUtil;
import com.huaxinkaiye.utils.SimpleClient;
import com.huaxinkaiye.utils.ToastUtil;
import com.huaxinkaiye.utils.UrlUtils;
import com.huaxinkaiye.widget.SimpleFooter;
import com.huaxinkaiye.widget.SimpleHeader;
import com.huaxinkaiye.widget.ZrcListView;
import com.huaxinkaiye.widget.ZrcListView.OnStartListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ChuJianListActivity<KeyEvent> extends Activity implements
		OnClickListener, com.huaxinkaiye.widget.ZrcListView.OnItemClickListener {
	private ZrcListView listView;
	private ImageView im_home, im_shuaxin, im_saomiao, im_sousuo;
	private EditText ed_sousuo;
	private ListAdapter chujianadapter;
	public ProgressUtil progress;
	public List<NameValuePair> params;
	public int pageNo = 1;
	public int pageSize = 30;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				progress.dismiss();
				jiexiListData(msg.obj.toString());
				break;
			case 2:
				progress.dismiss();
				JiexiSousuoData(msg.obj.toString());
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chujian);
		progress = new ProgressUtil(this, "正在获取数据");
		initView();
	}

	protected void jiexiListData(String s) {
		// TODO Auto-generated method stub
		if (pageNo == 1) {
			chujianadapter.clear();
			chujianadapter.notifyDataSetChanged();
		}
		JSONObject json;
		try {
			json = new JSONObject(s);
			// Log.e("s.substring(558, 585)", s.substring(500, 580));
			Gson gson = new Gson();
			ListBean listbean = gson.fromJson(s, ListBean.class);
			if (listbean.getPageNo() == 0) {
				listView.stopLoadMore();
				// listView.setRefreshFail("failds");
				// listView.clearAnimation();
			}
			if (listbean.getTotalRows() == 0) {
				ToastUtil.show(this, "没有数据");
			}
			chujianadapter.add(listbean.getRows());
			chujianadapter.notifyDataSetChanged();
			listView.setRefreshSuccess("success");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void JiexiSousuoData(String s) {
		// TODO Auto-generated method stub
		// if (pageNo == 1) {

		// }
		JSONObject json;
		try {
			json = new JSONObject(s);
			// Log.e("s.substring(558, 585)", s.substring(500, 580));
			Gson gson = new Gson();
			ListBean listbean = gson.fromJson(s, ListBean.class);
			if (listbean.getRows().size() == 0) {
				Intent intent = new Intent(this, ChuJianFaildsActivity.class);
				startActivity(intent);
			} else {
				if (listbean.getPageNo() == 0) {
					listView.stopLoadMore();
					listView.setRefreshFail("failds");
				}
				chujianadapter.clear();
				chujianadapter.add(listbean.getRows());
				chujianadapter.notifyDataSetChanged();
				listView.setRefreshSuccess("success");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initView() {
		// TODO Auto-generated method stub
		listView = (ZrcListView) findViewById(R.id.zListView);
		im_home = (ImageView) findViewById(R.id.im_home);
		im_shuaxin = (ImageView) findViewById(R.id.im_shuaxin);
		im_shuaxin.setOnClickListener(this);
		im_saomiao = (ImageView) findViewById(R.id.im_saomiao);
		im_saomiao.setOnClickListener(this);
		im_sousuo = (ImageView) findViewById(R.id.im_sousuo);
		im_sousuo.setOnClickListener(this);
		ed_sousuo = (EditText) findViewById(R.id.ed_sousuo);
		// ed_sousuo.setOnKeyListener(new OnKeyListener()
		// {//输入完后按键盘上的搜索键【回车键改为了搜索键】
		//
		// @Override
		// public boolean onKey(View arg0, int arg1, android.view.KeyEvent arg2)
		// {
		// // TODO Auto-generated method stub
		// if(arg1==arg2.KEYCODE_ENTER){//修改回车键功能
		// // 先隐藏键盘
		// ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
		// .hideSoftInputFromWindow(ChuJianListActivity.this
		// .getCurrentFocus()
		// .getWindowToken(),
		// InputMethodManager.HIDE_NOT_ALWAYS);
		// }
		// return false;
		// }
		// });
		// 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
		SimpleHeader header = new SimpleHeader(this);
		header.setTextColor(0xff0066aa);
		header.setCircleColor(0xff33bbee);
		listView.setHeadable(header);

		// 设置加载更多的样式（可选）
		SimpleFooter footer = new SimpleFooter(this);
		footer.setCircleColor(0xff33bbee);
		listView.setFootable(footer);

		// 设置列表项出现动画（可选）
		listView.setItemAnimForTopIn(R.anim.zrclistview_topitem_in);
		listView.setItemAnimForBottomIn(R.anim.zrclistview_bottomitem_in);

		// 下拉刷新事件回调（可选）
		listView.setOnRefreshStartListener(new OnStartListener() {
			@Override
			public void onStart() {
				pageNo = 1;
				refresh(pageNo);
			}
		});

		// 加载更多事件回调（可选）
		listView.setOnLoadMoreStartListener(new OnStartListener() {
			@Override
			public void onStart() {
				pageNo++;
				refresh(pageNo);
			}
		});

		chujianadapter = new ListAdapter(this);
		listView.setAdapter(chujianadapter);

		listView.refresh(); // 主动下拉刷新

		listView.setOnItemClickListener(this);
	}

	// protected void loadMore() {
	// // TODO Auto-generated method stub
	// pageNo++;
	//
	// }

	protected void refresh(int pageNo) {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
			progress.show();
			params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("pageNo", pageNo + ""));
			params.add(new BasicNameValuePair("pageSize", pageSize + ""));
			params.add(new BasicNameValuePair("sort", "id"));
			params.add(new BasicNameValuePair("direction", "desc"));
			params.add(new BasicNameValuePair("plateNumber", ""));
			// params.add(new BasicNameValuePair("recordNo","recordNo"));
			new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					String data;
					try {
						data = SimpleClient.doPost(UrlUtils.chujianlist_url,
								params);
						Log.e("chujianlist_data", data);
						Message mes = new Message();
						mes.what = 1;
						mes.obj = data;
						handler.sendMessage(mes);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
		} else {
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// refresh(1);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.im_home:
			break;
		case R.id.im_saomiao:
			Intent intent = new Intent(this, CaptureActivity.class);
			startActivityForResult(intent, 100);
			break;
		case R.id.im_shuaxin:
			refresh(1);
			break;
		case R.id.im_sousuo:
			pageNo = 1;
			searchD(ed_sousuo.getText().toString());
			break;
		}
	}

	@Override
	public void onItemClick(ZrcListView parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		RowsBean rowsBeanInfo = (RowsBean) parent.getAdapter()
				.getItem(position);
		Intent intent = new Intent(this, ChuJianDengJiActivity.class);
		intent.putExtra("rowsBeanInfo", rowsBeanInfo);
		startActivityForResult(intent, 101);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		/**
		 * 拿到解析完成的字符串
		 */
		Log.e("requestCode, int resultCode, Intent data", requestCode + "---"
				+ resultCode + "---");
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 101:
				refresh(1);
				break;
			case 100:
				if (data != null) {
					String saoma = data.getStringExtra("result");
					Log.e("chujian_saoma", saoma);
					ed_sousuo.setText(saoma);
					searchD(saoma);
				}
				break;
			}
		}
	}

	protected void searchD(String sousuo) {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
			progress.show();
			pageNo = 1;
			params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("pageNo", pageNo + ""));
			params.add(new BasicNameValuePair("pageSize", pageSize + ""));
			params.add(new BasicNameValuePair("sort", "id"));
			params.add(new BasicNameValuePair("direction", "desc"));
			params.add(new BasicNameValuePair("plateNumber", sousuo));
			params.add(new BasicNameValuePair("recordNo", sousuo));
			new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					String data;
					try {
						data = SimpleClient.doPost(UrlUtils.chujianlist_url,
								params);
						Log.e("search_chujianlist_data", data);
						Message mes = new Message();
						mes.what = 2;
						mes.obj = data;
						handler.sendMessage(mes);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
		} else {
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
		}
	}
}
